package com.xjscrm.server.service.grouppulljob.impl;

import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.uzai.trace.TraceGenerate;
import com.xjscrm.common.annotation.MerId;
import com.xjscrm.common.entity.GroupPullJob;
import com.xjscrm.common.utils.DateUtil;
import com.xjscrm.common.utils.Tools;
import com.xjscrm.server.biz.RatelimitService;
import com.xjscrm.server.dto.grouppulljob.GroupPullJobQuery;
import com.xjscrm.server.dto.grouppulljobmsg.GroupPullJobMsgQuery;
import com.xjscrm.server.mapper.GroupPullJobMapper;
import com.xjscrm.server.mapper.GroupPullJobMsgMapper;
import com.xjscrm.server.mapper.GroupPullTaskMapper;
import com.xjscrm.server.service.grouppulljob.GroupPullJobService;
import com.xjscrm.server.service.grouppulljob.GroupPullJobSyncService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 群发任务异步实现类
 *
 * @author makejava
 * @since 2024-03-01 17:01:12
 */
@Slf4j
@Service
public class GroupPullJobSyncServiceImpl implements GroupPullJobSyncService {

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private GroupPullTaskMapper groupPullTaskMapper;
    @Autowired
    private RatelimitService ratelimitService;
    @Autowired
    private GroupPullJobService groupPullJobService;
    @Autowired
    private GroupPullJobMapper groupPullJobMapper;
    @Autowired
    private GroupPullJobMsgMapper groupPullJobMsgMapper;

    /**
     * 处理群发任务的消息
     * @param merId
     * @return null
     * @author jitwxs
     * @date 2024/3/8 17:12
     */
    @Async("taskExecutorForXxJob")
    public void groupPullJobSendData(@MerId Long merId){
        //限流key
        String taskLimitKet = "-groupPullJobSendData-taskLimitKey-merId=" + merId;
        Object object = redisTemplate.opsForValue().get(taskLimitKet);
        if (object != null) {
            return;
        }
        //保存限流key
        redisTemplate.opsForValue().set(taskLimitKet, taskLimitKet, 100, TimeUnit.SECONDS);

        log.info("-----处理群发任务的消息----merId=" + merId);

        try {
            //查询当前所有开启的自动发圈的配置方案
            int now = DateUtil.getTime();
            GroupPullJobQuery groupPullJobQuery = new GroupPullJobQuery();
            groupPullJobQuery.setMerId(merId);
            groupPullJobQuery.setStatus(1); //进行中
            groupPullJobQuery.setStartSendTimeEnd(now);
            //查询所有的自动发圈配置记录
            Page<GroupPullJob> page = new Page<>();
            page.setCurrent(1);//只查第一页
            page.setSize(10); //每页查询10个
            page.addOrder(OrderItem.asc("id"));//默认id升序
            Long idStart = 0L;
            List<GroupPullJob> groupPullJobList = groupPullJobMapper.findByList(page, groupPullJobQuery);
            while (groupPullJobList != null && groupPullJobList.size() > 0) {
                for (GroupPullJob groupPullJob : groupPullJobList) {
                    if (groupPullJob.getId().longValue() >idStart.longValue()) {
                        idStart = groupPullJob.getId();
                    }

                    //限流判断
                    String rateLimitKey = "groupPullJobSendData-jobId=" + groupPullJob.getId();
                    Object rateLimitKeyobject = redisTemplate.opsForValue().get(rateLimitKey);
                    if (rateLimitKeyobject == null) {
                        //保存限流key
                        redisTemplate.opsForValue().set(rateLimitKey, rateLimitKey, 300, TimeUnit.SECONDS);
                    } else {
                        continue;
                    }
                    try {

                        //判断此任务是否还有未发送的消息，如果没有了，则修改成已完成
                        GroupPullJobMsgQuery groupPullJobMsgQuery = new GroupPullJobMsgQuery();
                        groupPullJobMsgQuery.setMerId(merId);
                        groupPullJobMsgQuery.setJobId(groupPullJob.getId());
                        groupPullJobMsgQuery.setStatus(1); //查询该机器人还是否有未发送的消息
                        Integer count = Tools.getInteger(groupPullJobMsgMapper.findCount(groupPullJobMsgQuery));
                        if(count.intValue() == 0 && Tools.getInteger(groupPullJob.getStartSendTime().intValue()) < now - 180){//此任务已经没有未发送的消息，将任务修改成已完成
                            groupPullJob.setStatus(2);//状态（1-发送中；2-已完成；3-已暂停；4-已取消)
                            groupPullJob.setUpdateTime(DateUtil.getTime());
                            groupPullJobMapper.updateById(groupPullJob);
                            continue;
                        }

                        //处理群发任务的消息
                        groupPullJobService.groupPullJobSendData(groupPullJob);

                    } catch (Exception e) {
                        log.error("--封装群发任务消息失败--error={}", e.getMessage(), e);
                    }finally {
                        //保存成功之后，手动删除限流redisKey
                        redisTemplate.delete(rateLimitKey);
                    }
                }

                groupPullJobQuery.setIdStart(idStart);
                groupPullJobList = groupPullJobMapper.findByList(page, groupPullJobQuery);
            }
        } catch (Exception e) {
            log.info(e.getMessage(),e);
        } finally {
            //删除限流key
            redisTemplate.delete(taskLimitKet);
        }

    }
}
